package com.elite.groovy.callback

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import com.elite.groovy.util.EliteBean
import cn.com.elite.PropertiesUtil
import cn.com.kh.HttpClientProxy
import net.sf.json.JSONArray
import net.sf.json.JSONObject

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

class RobotReservation implements ServiceBackInvoke {

	private static final Log log=LogFactory.getLog(RobotReservation.class);

	@Override
	public String doCallBack(EliteBean elite, HttpServletRequest request, HttpServletResponse response) {
		log.debug("开始启动机器人预约名单下发");
		JSONObject result = new JSONObject();
		long startTime=System.currentTimeMillis();
		def count = 0;
		try {
			//获取配置文件中配置好的企业号、代理ip及端口
			PropertiesUtil cfg = new PropertiesUtil();
			def Te_entId = cfg.readValue("QingNiu.EntId");
			String proxyIp = cfg.readValue("QingNiu.ProxyIP");
			int proxyPort=0;
			if(cfg.readValue("QingNiu.ProxyPort")!=null&&cfg.readValue("QingNiu.ProxyPort")!="") {
				proxyPort = cfg.readValue("QingNiu.ProxyPort").toInteger();
			}
			/*
			 * 根据名单拨打次数为预约状态的attempt>0并且是机器人批次的、
			 * 时间范围为预约当天及当天之前的预约名单或者是预约时间大于等于3天的预约名单加入到临时表中
			 * 预约待推送标记is_push=2
			 */
			String addReservationTemporarySql = "insert into robot_push_temporary(id,customer_guid,customer_name,mobile,tel_1,atel_1,atel_2,atel_3,atel_4,createddate,createdby,in_enddate,custlist,robot_activity_name,is_push,send_type,objective_guid) select sys_guid(), t.* from (select distinct c.customer_guid,c2.customername,c2.mobile,c2.tel_1,c2.atel_1,c2.atel_2,c2.atel_3,c2.atel_4,sysdate,'SELITE',c.in_enddate,c.stringfield1, b.reservation_activity,'2','3',objective_guid from elitetask e left join customer c on c.customer_guid = e.customer_guid left join customer c2 on c.parent_guid = c2.customer_guid inner join list_standard_rule sr  on e.custlistname = sr.custlist_name inner join Batch_configuration b on sr.Yc_Reservation_Id = b.id left join authority_relationship a on e.handlegroup_id = a.lower where 1 = 1  and ((e.expectstarttime <= (TRUNC(SYSDATE) + 1 - 1 / 86400)) or e.expectstarttime >= trunc(sysdate + 3))  and e.handleby_id is not null and e.attempt > 0 and e.elitetaskstatus <> 'APCALL' and c.customertype2_id = '000002' and c.stringfield16 is null and trunc(c.In_Enddate) - trunc(sysdate) > 7 and c.customer_guid not in (select distinct customer_guid from robot_Push_History lh left join custlists cl on lh.Custlist = cl.CUSTLIST_XXX where send_type = '3')  and e.handlegroup_id not in (select c.createdgroup from c_freedate c where c.freedate = trunc(sysdate)) and a.Higher not in (select c.createdgroup from c_freedate c where c.freedate = trunc(sysdate))) t";
			int reservationTemporaryRow = elite.update(addReservationTemporarySql, "dataSource");
			log.debug("机器人当日应推送预约数量(当日+当日之前的预约):"+reservationTemporaryRow);
			if(reservationTemporaryRow > 0) {
				String selectSQL3="select WEBSERVICEURL from sysc_interface where webtype='QN_MDDR'";

				def postURL2=elite.chaxun_sql(selectSQL3, "dataSource");
				def httpURL=postURL2[0].get("WEBSERVICEURL");
				log.debug("青牛地址:"+httpURL);
				JSONObject dataObject2 = null;
				def sendNum=2700; //每批数据分批推送条数
				def con = Math.ceil(reservationTemporaryRow/sendNum);
				for(int q=1;q<=con;q++) {
					def temp_id=UUID.randomUUID().toString();
					def updateSQL1="update robot_push_temporary set Is_push='1',temp_id='"+temp_id+"' where Is_push='2' and send_type =3 and rownum<='"+sendNum+"'";
					int row4=elite.update(updateSQL1,"dataSource");

					//将临时表中标记为预约待下发(is_push标记为2)的名单查询出来转为报文推送给青牛
					String sqls="select distinct t.* from (select l.customer_guid custId,"+Te_entId+" ENTID,l.robot_activity_name CALLLISTNAME,l.customer_guid recordKey,l.mobile,l.tel_1,l.atel_1,l.atel_2,l.atel_3,l.atel_4,s.Agent_Id,s.Staff_Id,l.objective_guid,e.handlegroup_id from robot_push_temporary l left join elitetask e on l.objective_guid = e.objective_guid left join staff s on e.handleby_id = s.Staff_Id left join Authority_Relationship ar on e.handlegroup_id = ar.lower where l.Is_push = '1'and l.send_type = '3' and l.temp_id = '"+temp_id+"' and e.objective_guid is not null and e.handlegroup_id not in (select c.createdgroup from c_freedate c where c.freedate = trunc(sysdate)) and ar.Higher not in (select c.createdgroup from c_freedate c where c.freedate = trunc(sysdate)) order by in_enddate asc)t";
					def resultlist2= elite.chaxun_sql(sqls, "dataSource");

					JSONArray jsonArray2=JSONArray.fromObject(resultlist2);
					def ListNum2 = jsonArray2.size();
					JSONArray arr = new JSONArray();
					JSONObject obj = new JSONObject();
					JSONObject dataObject= null;;
					log.debug("temp_id:"+temp_id+"本次调用数量:"+ListNum2);
					if(ListNum2 > 0){
						for(int j=0;j<ListNum2;j++) {
							dataObject=jsonArray2.getJSONObject(j);
							def cust_id=GetJV(dataObject, "CUSTID");
							def entId=GetJV(dataObject, "ENTID");
							def activity_id=GetJV(dataObject, "CALLLISTNAME");
							def recordKey=GetJV(dataObject, "RECORDKEY");
							def objectiveGuid = GetJV(dataObject, "OBJECTIVE_GUID");
							def agentId = GetJV(dataObject, "AGENT_ID");
							def staffId = GetJV(dataObject, "STAFF_ID");
							def phoneNumber1=GetJV(dataObject, "MOBILE");
							def phoneNumber2=GetJV(dataObject, "TEL_1");
							def phoneNumber3=GetJV(dataObject, "ATEL_1");
							def phoneNumber4=GetJV(dataObject, "ATEL_2");
							def phoneNumber5=GetJV(dataObject, "ATEL_3");
							def phoneNumber6=GetJV(dataObject, "ATEL_4");
							if(objectiveGuid==null || objectiveGuid=="") {
								continue;
							}
							JSONObject phoneNumbers = new JSONObject();
							phoneNumbers.put("phoneNumber1", phoneNumber1);
							phoneNumbers.put("phoneNumber2", phoneNumber2);
							phoneNumbers.put("phoneNumber3", phoneNumber3);
							phoneNumbers.put("phoneNumber4", phoneNumber4);
							phoneNumbers.put("phoneNumber5", phoneNumber5);
							phoneNumbers.put("phoneNumber6", phoneNumber6);
							obj.put("custId", cust_id+","+objectiveGuid);
							obj.put("entId", entId);
							obj.put("callListName", activity_id);
							obj.put("recordKey", recordKey);
							obj.put("phoneNumbers", phoneNumbers);
							obj.put("exData3",agentId);
							obj.put("exData4",staffId);
							obj.put("exData5",objectiveGuid);
							obj.put("exData6",objectiveGuid);

							arr.add(obj);
						}

						//推送数据
						def id=UUID.randomUUID().toString();
						JSONObject objtwo = new JSONObject();
						objtwo.put("batchId", id);
						objtwo.put("total", ListNum2);
						objtwo.put("data", arr);

						long time=System.currentTimeMillis();
						def reJson = HttpClientProxy.sendPost(httpURL, objtwo.toString(),proxyIp,proxyPort);
						log.debug(id+"本次调用返回结果:"+reJson);
						JSONObject json = new JSONObject().fromObject(reJson);
						long etime=System.currentTimeMillis();
						log.debug(id+"本次调用时间耗时:"+(etime - startTime)+"毫秒");

						String code=json.code;
						StringBuffer sql = new StringBuffer("insert into robot_push_history ");
						sql.append("(id,customer_guid,is_flag,robot_activity_name,custlist,");
						sql.append("createddate,mobile,tel_1,atel_1,atel_2,atel_3,atel_4,customer_name,send_type,in_enddate,objective_guid) ");
						sql.append("select sys_guid(),customer_guid,'"+code+"', robot_activity_name,custlist,");
						sql.append("sysdate,mobile,tel_1,atel_1,atel_2,atel_3,atel_4,customer_name,send_type,in_enddate,objective_guid ");
						sql.append("from robot_push_temporary where is_push='1' and send_type =3 and temp_id='"+temp_id+"'");
						def row7=elite.update(sql.toString(),"dataSource");
						log.debug(id+"本次推送记录至历史表数量:"+row7);
						count+=row7;

						def deleteSQL1="delete from robot_push_temporary where is_push='1' and send_type=3 and temp_id='"+temp_id+"' and Listrank is null"
						int row6=elite.update(deleteSQL1,"dataSource");
						log.debug(id+"本次推送清除临时表数量:"+row6);
					}

					long endTime=System.currentTimeMillis();
					result.put("code", 1);
					result.put("msg", "处理完成、调用处理时长(毫秒):" + (endTime - startTime) + "共推送" + count + "条");
					log.debug("机器人预约名单下发结束");
				}
			}else {
				result.put("code", 1007);
				result.put("msg", "当前日期是没有预约名单，不流入");
			}
		}catch(Exception e) {
			result.put("code", 1008);
			result.put("msg", e.getMessage());
		}
	}

	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null
		try {
			Rev_Value = inJson.getString(getKey)
			//log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey))
				//log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
			} catch (Exception e1) {
				Rev_Value = ""
				//log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				//log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
				Rev_Value = ""
			}
		}
		return Rev_Value
	}
}